<template>
  <div class="app-container">
    <el-form ref="filterForm" :inline="true" :model="listQuery" class="filter-container">
      <el-form-item prop="message">
        <el-input v-model="listQuery.message" size="small" placeholder="内容" clearable style="width: 200px;" @keyup.enter.native="handleFilter" />
      </el-form-item>

      <el-form-item>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-search"
          @click="handleFilter"
        >筛选</el-button>
        <el-button
          size="small"
          @click="resetFilter"
        >重置</el-button>
        <el-divider direction="vertical" />
        <el-switch
          v-model="meetingNotes"
          active-text="开启小纸条"
          :active-value="1"
          :inactive-value="0"
          @change="switchMeetingNotes"
        />
      </el-form-item>
    </el-form>

    <el-card class="box-card">
      <div slot="header" class="card-header clearfix">
        <h5 class="title pull-left">{{ meetingData.meetingtitle }} 互动小纸条</h5>
        <el-button
          type="text"
          icon="el-icon-notebook-2"
          size="small"
          class="btn pull-right"
          @click="toMeetingShow"
        >会议详情</el-button>
      </div>

      <div class="card-wrapper">
        <div
          v-loading="listLoading"
          element-loading-text="Loading"
          class="chat-list"
        >
          <div
            v-for="item in list"
            :key="item.id"
            class="chat-list-item"
          >
            <div class="media-left">
              <avatar :img-width="40" :avatar-uri="item.photo" alt="" />
            </div>
            <div class="media-body">
              <div class="clearfix">
                <div class="nickname pull-left">{{ item.nickname }} 发表了评论:</div>
                <div class="pull-right">{{ item.createTime | moment('YYYY-MM-DD HH:mm:ss') }}</div>
              </div>
              <div class="chat-detail" v-html="item.message" />
              <!-- <div class="check-area">
                <el-button size="mini" plain  type="success">审核通过</el-button>
                <el-button size="mini" plain  type="danger">审核不通过</el-button>
              </div> -->
            </div>
          </div>
        </div>

        <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.size" @pagination="fetchData" />
      </div>
    </el-card>
  </div>
</template>

<script>
import {
  getMeetingNotes,
  switchMeetingNotes
} from '@/api/surveys'
import {
  getMeetingShow
} from '@/api/meetings'
import Pagination from '@/components/Pagination'
import Avatar from '@/components/Avatar'
import WebsocketHeartbeatJs from 'websocket-heartbeat-js'

export default {
  name: 'MeetingNotesList',
  components: {
    Avatar,
    Pagination
  },
  data() {
    return {
      websock: null,
      websockPingMsg: 'heartbeat',
      meetingNotes: 0,
      meetingData: {},
      list: null,
      listLoading: true,
      total: 0,
      listQuery: {
        meetingId: undefined,
        message: undefined,
        page: 1,
        size: 20
      }
    }
  },
  watch: {
    $route: {
      handler(route) {
        this.meetingId = route.params && route.params.id
      },
      immediate: true
    }
  },
  created() {
    this.meetingId = this.$route.params.id
    this.listQuery.meetingId = this.$route.params.id
    this.fetchData()
    this.fetchMeetingData()
  },
  destroyed() {
    if (this.meetingNotes === 1) {
      this.websock.close()
    }
  },
  methods: {
    fetchData() {
      this.listLoading = true
      getMeetingNotes(this.listQuery).then(response => {
        // console.log(response)
        this.list = response.data
        this.total = response.total
        this.listLoading = false
      }).catch(err => {
        console.log(err)
      })
    },
    fetchMeetingData() {
      getMeetingShow({
        id: this.meetingId
      }).then(response => {
        const { data } = response
        // console.log(data)
        this.meetingData = data
        this.meetingNotes = data.notes
        if (data.notes === 1) {
          this.initWebSocket()
        }
      }).catch(err => {
        console.log(err)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.list = []
      this.fetchData()
    },
    resetFilter() {
      this.$refs.filterForm.resetFields()
      this.handleFilter()
    },
    switchMeetingNotes() {
      switchMeetingNotes({
        id: this.meetingId,
        notes: this.meetingNotes
      }).then(response => {
        // console.log(response)
        if (this.meetingNotes === 1) {
          this.initWebSocket()
        } else {
          this.websock.close()
        }
        this.$message({
          type: 'success',
          message: '设置成功!'
        })
      }).catch(err => {
        console.log(err)
      })
    },
    toMeetingShow() {
      this.$router.push(`/meetings/list/${this.meetingId}?type=invite`)
    },
    initWebSocket() {
      const options = {
        url: `${process.env.VUE_APP_WEBSOCKET}${this.meetingId}`,
        pingTimeout: 15000,
        pongTimeout: 10000,
        reconnectTimeout: 2000,
        pingMsg: this.websockPingMsg
      }
      this.websock = new WebsocketHeartbeatJs(options)
      this.websock.onopen = this.websocketonopen
      this.websock.onerror = this.websocketonerror
      this.websock.onmessage = this.websocketonmessage
      this.websock.onclose = this.websocketonclose
      this.websock.onreconnect = this.websocketonreconnect
    },
    websocketonopen() {
      console.log('websocket open success')
    },
    websocketonerror() {
      console.log('websocket connect onerror')
    },
    websocketonmessage(e) {
      console.log('msg:', e.data)
      if (e.data !== '连接成功' && e.data !== this.websockPingMsg) {
        const msgData = JSON.parse(e.data)
        // console.log(msgData)
        this.list.unshift(msgData)
      }
    },
    websocketsend(data) {
      this.websock.send(data)
    },
    websocketonclose() {
      console.log('websocket connect close')
    },
    websocketonreconnect() {
      console.log('websocket reconnecting...')
    }
  }
}
</script>

<style lang="scss" scoped>
.chat-list-item {
  display: flex;
  padding-top: 20px;
  border-bottom: 1px solid #e7eaec;
  .media-body {
    flex: 1;
    padding-left: 16px;
    font-size: 14px;
    color: #606266;
    .nickname {
      font-weight: bold;
    }
    .chat-detail {
      line-height: 16px;
      min-height: 20px;
      padding: 10px 16px;
      margin-top: 6px;
      margin-bottom: 20px;
      border: 1px solid #e3e3e3;
      border-radius: 4px;
      box-shadow: inset 0 1px 1px rgba(0, 0, 0, .05);
      background-color: #f5f5f5;
      .note-img {
        max-height: 200px;
        margin: 0 8px 8px 0;
      }
    }
    .check-area {
      margin-bottom: 20px;
      text-align: right;
    }
  }
}
</style>
